<?php

namespace App\Http\Controllers\App\Quiz;

use App\Http\Controllers\App\AppInterface;
use App\Http\Controllers\App\Controller;
use App\Http\Requests\Request;

class QuizController extends Controller implements AppInterface
{
    public function luckDraw(Request $request)
    {
        $activityId = $request->request->get('activity_id');
        $openId = $request->request->get('openid');
        $redPack = $request->request->get('redpack');

        if (!$openId) {
            return $this->error('请登录后参加活动');
        }

        if (!$redPack) {
            return $this->error('不满足参与活动条件');
        }

        $activity = $this->getActivityDetail($activityId);
        $now = time();

        if ($now < strtotime(array_get($activity, 'startTime'))) {
            return $this->error('活动还没开始');
        }

        if ($now > strtotime(array_get($activity, 'endTime'))) {
            return $this->error('活动已经结束');
        }

        $rule = \GuzzleHttp\json_decode(array_get($activity, 'rule'), true);

        if ($redPack < array_get($rule, 'basic.min_num')) {
            return $this->error('不满足参与活动条件');
        }

        $prize = $this->getLuckPrizeByActivity($activityId, $openId->id);

        return $this->respondJson($prize);
    }

    public function activity()
    {
        // TODO: Implement activity() method.
    }

    public function preview($model, $template)
    {
        // TODO: Implement preview() method.
    }

    protected function error($message)
    {
        return $this->respondJson([
            'code' => ExceptionCode::GENERAL,
            'message' => $message,
        ]);
    }
}
